//
//  UIView+Tracking.m
//  runtime
//
//  Created by soulghost on 6/1/2016.
//  Copyright © 2016 soulghost. All rights reserved.
//

#import "UIView+Tracking.h"
#import <objc/runtime.h>
#import "UIView+Night.h"
#import "UIButton+Night.h"

@implementation UIView (Tracking)

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        
        SEL oriSEL = @selector(layoutSubviews);
        SEL swiSEL = @selector(track_layoutSubviews);
        
        Method oriMethod = class_getInstanceMethod(class, oriSEL);
        Method swizMethod = class_getInstanceMethod(class, swiSEL);
        
        BOOL didAddMethod = class_addMethod(class, oriSEL, method_getImplementation(swizMethod), method_getTypeEncoding(swizMethod));
        if (didAddMethod) {
            class_replaceMethod(class, swiSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
        }else{
            method_exchangeImplementations(oriMethod, swizMethod);
        }
        
    });
}

- (void)track_layoutSubviews{
    [self track_layoutSubviews];
    if (self.tintColor == nil) {
        return;
    }
    NSLog(@"%@ %d",[self class], self.tintColor == [UIColor blueColor]);
    UIColor *normalColor = self.tintColor;
    NSLog(@"%@",normalColor);
    const CGFloat *comps = CGColorGetComponents(normalColor.CGColor);
    for (int i = 0; i < 3; i++) {
        CGFloat value = comps[i];
        value = 255 - value;
    }
    CGColorRef nightColorRef = CGColorCreate(CGColorSpaceCreateDeviceRGB(), comps);
    UIColor *nightColor = [UIColor colorWithCGColor:nightColorRef];
    DKColorPicker picker = DKColorWithColors([UIColor blackColor], nightColor);
    if ([self isKindOfClass:[UIButton class]]) {
        UIButton *btn = (UIButton *)self;
        [btn dk_setTitleColorPicker:picker forState:UIControlStateNormal];
    }else{
        self.dk_tintColorPicker = picker;
    }
    CFRelease(nightColorRef);
}

@end
